package com.gxcommunication.sociallearn.modules.splash;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.gxcommunication.sociallearn.modules.main.MainActivity;
import com.gxcommunication.sociallearn.R;
import com.gxcommunication.sociallearn.api.ServiceApi;
import com.gxcommunication.sociallearn.config.ConfigUtils;
import com.gxcommunication.sociallearn.http.service.ApiStore;
import com.gxcommunication.sociallearn.utils.IntentUtils;
import com.gxcommunication.sociallearn.utils.LogHelper;
import com.mylhyl.acp.Acp;
import com.mylhyl.acp.AcpListener;
import com.mylhyl.acp.AcpOptions;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

public class FlashActivity extends Activity {
    RelativeLayout flashLayout;
    TextView versionTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_flash);
        flashLayout = findViewById(R.id.flash_layout);
        versionTv = findViewById(R.id.versionTv);

//        getSystemThemeCOlorInfo();//配置一键置灰

        try {
            String versionName = this.getPackageManager().getPackageInfo(
                    this.getPackageName(), 0).versionName;
            versionTv.setText("V " + versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        //凹形屏幕刘海屏的显示模式配置，如果不设置头部刘海的位置会有黑边或者无法显示布局
        if (Build.VERSION.SDK_INT >= 28) {
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
            getWindow().setAttributes(lp);
        }

    }

    private static void setTransparentForWindow(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            activity.getWindow().setStatusBarColor(Color.TRANSPARENT);
            activity.getWindow()
                    .getDecorView()
                    .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            activity.getWindow()
                    .setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 渐变展示启动屏
        AlphaAnimation animation = new AlphaAnimation(0.5f, 1.0f);
        animation.setDuration(2000);
        flashLayout.startAnimation(animation);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationEnd(Animation arg0) {

                checkUserAgreeMent();

            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }

            @Override
            public void onAnimationStart(Animation animation) {

            }

        });

    }

    public void downloadFile(String url, final String savePatch, final String fileName) {
        ApiStore.createApi(ServiceApi.class)
                .downloadImg(url)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.newThread())
                .map(new Function<ResponseBody, String>() {

                    @Override
                    public String apply(ResponseBody responseBody) throws Exception {
                        Bitmap bitmap = null;
                        String savePath = savePatch + fileName;
                        byte[] bys;
                        try {
                            bys = responseBody.bytes();
                            bitmap = BitmapFactory.decodeByteArray(bys, 0, bys.length);

                            File file = new File(savePath);
                            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
                            bos.flush();
                            bos.close();

                        } catch (IOException e) {
                            e.printStackTrace();
                            return "";
                        }

                        if (bitmap != null) {
                            bitmap.recycle();
                        }
                        return savePath;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DisposableObserver<String>() {
                    @Override
                    public void onNext(String responseBody) {


                    }

                    @Override
                    public void onError(Throwable e) {
                        //你的处理
                        LogHelper.e("onError" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //你的处理
                    }
                });
    }


    private void checkUserAgreeMent() {
//        if (SharePreferenceUtils.getFirstOpenUserAgreement()) {

//            new SYDialog.Builder(FlashActivity.this)
//                    .setDialogView(R.layout.dialog_user_agreement_layout)
//                    .setScreenWidthP(0.90f)
//                    .setGravity(Gravity.CENTER)
//                    .setCancelable(false)
//                    .setCancelableOutSide(false)
//                    .setAnimStyle(R.style.AnimUp)
//                    .setBuildChildListener(new IDialog.OnBuildListener() {
//                        @Override
//                        public void onBuildChildView(final IDialog dialog, View view, int layoutRes) {
//                            view.findViewById(R.id.btnCancel).setOnClickListener(new View.OnClickListener() {
//
//                                @Override
//                                public void onClick(View v) {
//                                    dialog.dismiss();
//                                    finish();
//                                }
//                            });
//
//                            view.findViewById(R.id.btnOk).setOnClickListener(new View.OnClickListener() {
//
//
//                                @Override
//                                public void onClick(View v) {
//                                    SharePreferenceUtils.setFirstOpenUserAgreementToFalse();
//                                    getCameraPermission();
//                                    dialog.dismiss();
//
//                                }
//                            });
//
//                            view.findViewById(R.id.tv_user_agreement).setOnClickListener(new View.OnClickListener() {
//
//                                @Override
//                                public void onClick(View v) {
//                                    ARouter.getInstance().build(ARoutersConstant.PATH_COMMOM_WEB)
//                                            .withString("loadUrl", QueryUrl.xiexi)
//                                            .withString(AppConstant.TITLE, "用户及隐私协议")
//                                            .withInt(AppConstant.TYPE, 4)
//                                            .navigation();
//
//                                }
//                            });
//                        }
//                    }).show();
//        } else {
//            getCameraPermission();
//        }

        getCameraPermission();
    }

    /**
     * 请求引导图信息
     */
    private void getGuideInfo() {

//        ApiStore.createApi(ServiceApi.class)
//                .getSplashGuideInfo()
//                .compose(RxUtils.rxSchedulerHelper())
//                .subscribe(new HttpObserver<SplashGuideBean>() {
//
//                    @Override
//                    public void onSuccess(SplashGuideBean result) {
//                        if (result.getResult() == null || result.getResult().isEmpty()) {
////                            IntentUtils.startActivity(FlashActivity.this, MainFragmentTabActivity.class);
//                            finish();
//                        } else {
//                            CommonSharePreferenceUtils.setFirstOpenAppToFalse();
//                            ArrayList<String> stringList = new ArrayList<>();
//                            for (SplashGuideBean.ResultBean item : result.getResult()) {
//                                stringList.add(item.getStartImage());
//                            }
//                            Intent intent = new Intent(FlashActivity.this, GuideActivity.class);
//                            intent.putExtra(GuideActivity.INTENT_KEY_IMAGE_PATH, stringList);
//                            startActivity(intent);
//                            finish();
//                        }
//
//                    }
//
//                    @Override
//                    public void onFailed(int errorCode, String moreInfo) {
//                        super.onFailed(errorCode, moreInfo);
////                        IntentUtils.startActivity(FlashActivity.this, MainFragmentTabActivity.class);
//                        finish();
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
////                        IntentUtils.startActivity(FlashActivity.this, MainFragmentTabActivity.class);
//                        finish();
//                    }
//                });
    }

    private void getSystemThemeCOlorInfo() {
//        ApiStore.createApi(ServiceApi.class)
//                .getSystemConfigInfo("grayColor")
//                .compose(RxUtils.rxSchedulerHelper())
//                .subscribe(new HttpObserver<SystemConfigInfoBean>() {
//
//                    @Override
//                    public void onSuccess(SystemConfigInfoBean result) {
//                        if (result.getResult() == null){
//                            return;
//                        }
//
//                        if (result.getResult().getStatus() == 1) {
//                            SharePreferenceUtils.setSystemThemeInfo(true);
//
//                            Paint paint = new  Paint();
//                            ColorMatrix cm = new  ColorMatrix();
//                            cm.setSaturation(0f);
//                            paint.setColorFilter(new ColorMatrixColorFilter(cm));
//                            getWindow().getDecorView().setLayerType(View.LAYER_TYPE_HARDWARE, paint);
//
//                        } else {
//                            SharePreferenceUtils.setSystemThemeInfo(false);
//                        }
//                    }
//
//                    @Override
//                    public void onFailed(int errorCode, String moreInfo) {
//                        super.onFailed(errorCode, moreInfo);
//
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//
//                    }
//                });
    }


    private void getAdvertInfo() {
//        ApiStore.createApi(ServiceApi.class)
//                .getSplashAdvertInfo()
//                .compose(RxUtils.rxSchedulerHelper())
//                .subscribe(new HttpObserver<SplashAdvertBean>() {
//
//                    @Override
//                    public void onSuccess(SplashAdvertBean result) {
//                        if (result.getResult() == null) {
//                            IntentUtils.startActivity(FlashActivity.this, MainFragmentTabActivity.class);
//                            finish();
//                        } else {
//                            Intent intent = new Intent(FlashActivity.this, AdverActivity.class);
//                            intent.putExtra(AdverActivity.INTENT_KEY_DATA, result.getResult());
//                            startActivity(intent);
//                            finish();
//                        }
//                    }
//
//                    @Override
//                    public void onFailed(int errorCode, String moreInfo) {
//                        super.onFailed(errorCode, moreInfo);
//                        IntentUtils.startActivity(FlashActivity.this, MainFragmentTabActivity.class);
//                        finish();
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        IntentUtils.startActivity(FlashActivity.this, MainFragmentTabActivity.class);
//                        finish();
//                    }
//                });
    }

    private void getCameraPermission() {

        Acp.getInstance(this).request(new AcpOptions.Builder().setPermissions(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        ).build(), new AcpListener() {
            @Override
            public void onGranted() {

                IntentUtils.startActivity(FlashActivity.this, MainActivity.class);
                ConfigUtils.checkSystemFile();//检查是否存在app文件夹，没有则创建
                finish();

            }

            @Override
            public void onDenied(List<String> permissions) {
//                IntentUtils.startActivity(FlashActivity.this, MainFragmentTabActivity.class);
                finish();
            }
        });
    }
}
